<template>
  <div class="loginBox">
    <h3>用户登录</h3>
    <el-form :model="loginForm" :rules="rule" ref="loginFormRef">
      <el-form-item prop="username">
        <el-input v-model="loginForm.username" placeholder="请输入用户名">
          <template #prepend>
            <el-icon>
              <User />
            </el-icon>
          </template>
        </el-input>
      </el-form-item>

      <el-form-item prop="password">
        <el-input
          type="password"
          v-model="loginForm.password"
          placeholder="请输入密码"
          show-password
        >
          <template #prepend>
            <el-icon>
              <Lock />
            </el-icon>
          </template>
        </el-input>
      </el-form-item>

      <el-form-item
        prop="code"
        style="display: flex; justify-content: space-between"
      >
        <el-input
          v-model="loginForm.code"
          placeholder="请输入验证码"
          style="width: 80%"
        >
          <template #prepend>
            <el-icon>
              <Unlock />
            </el-icon> </template
        ></el-input>
        <img
          :src="codeUrl"
          alt=""
          style="width: 20%; height: 30px;cursor:pointer;"
          @click="refreshCode"
        />
      </el-form-item>

      <el-form-item>
        <el-checkbox
          v-model="loginForm.rememberPassword"
          label="记住密码"
          size="large"
        />
      </el-form-item>
      <el-button
        type="primary"
        :style="{ width: '100%' }"
        :loading="loading"
        @click="submit"
        ><span v-if="!loading">登录</span
        ><span v-else>登录中。。。</span></el-button
      >
    </el-form>
  </div>
</template>

<script>
import { getCode } from "@/api/login.js";
import { useRouter } from "vue-router";
import { ref, reactive, onMounted } from "vue";
import { userStore } from "@/store/user.js";
import Cookie from "js-cookie";
export default {
  name: "login",
  setup() {
    // 使用router对象才能使用push方法，记住这里定义的名称和上面引入的名称不能相同，否则会报错
    const myRouter = useRouter();

    // 登录表单
    const loginForm = reactive({
      username: Cookie.get("username") || "",
      password: Cookie.get("password") || "",
      rememberPassword: Boolean(Cookie.get("rememberPassword")),
      uuid: "",
    });

    // 验证码图片地址
    var codeUrl = ref("");

    // 获取验证码
    const getCodeFn = async () => {
      const { img = "", uuid = "" } = await getCode();
      codeUrl.value = "data:image/gif;base64," + img;
      loginForm.uuid = uuid;
    };
    getCodeFn();

    // 刷新验证码
    const refreshCode = () => {
      getCodeFn();
    };

    // 表单对象
    const loginFormRef = ref(null);
    // 用户Store
    const profileStore = userStore();
    // 登录loading
    const loading = ref(false);
    // 登录表单验证规则
    const rule = reactive({
      username: [
        { required: true, message: "请输入用户名", blur: true },
        { min: 3, message: "用户名不能少于3个字符" },
        { max: 10, message: "用户名不能超过10个字符" },
      ],
      password: [
        { required: true, message: "请输入密码" },
        { min: 3, message: "密码不能少于3个字符" },
        { max: 10, message: "密码不能超过10个字符" },
      ],
    });

    // 提交登录
    const submit = () => {
      loginFormRef.value.validate(async (valid) => {
        if (valid) {
          try {
            loading.value = true;
            await profileStore.login(loginForm);
            if (loginForm.rememberPassword) {
              Cookie.set("username", loginForm.username);
              Cookie.set("password", loginForm.password);
              Cookie.set("rememberPassword", loginForm.rememberPassword);
            } else {
              Cookie.remove("username");
              Cookie.remove("password");
              Cookie.remove("rememberPassword");
            }
            loading.value = false;
            myRouter.push("/");
          } catch (e) {
            loading.value = false;
            console.log(e);
          }
        }
      });
    };

    return {
      loginForm,
      loading,
      submit,
      profileStore,
      rule,
      loginFormRef,
      codeUrl,
      refreshCode,
    };
  },
};
</script>

<style scoped>
.loginBox {
  width: 400px;
  padding: 50px;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  background: #f2f2f2;
}

.loginBox h3 {
  margin-bottom: 20px;
  cursor: pointer;
}
</style>